package com.ruoyi.training.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.training.domain.*;
import com.ruoyi.training.dto.PracticeAppointmentDto;
import com.ruoyi.training.mapper.PracticeClassStudentMapper;
import com.ruoyi.training.service.*;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.PracticeAppointmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.mapper.PracticeAppointmentMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 实践预约Service业务层处理
 *
 * @author WorrilessGo
 * @date 2025-10-14
 */
@Service
public class PracticeAppointmentServiceImpl implements IPracticeAppointmentService {
    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    @Autowired
    private PracticeAppointmentMapper practiceAppointmentMapper;

    @Autowired
    private IProjectsService projectsService;

    @Autowired
    private IPracticeClassService practiceClassService;

    @Autowired
    private ITrainingClassService trainingClassService;

    @Autowired
    private PracticeClassStudentMapper practiceClassStudentMapper;

    /**
     * 查询实践预约
     *
     * @param practiceAppointmentId 实践预约主键
     * @return 实践预约
     */
    @Override
    public PracticeAppointment selectPracticeAppointmentByPracticeAppointmentId(String practiceAppointmentId) {
        return practiceAppointmentMapper.selectPracticeAppointmentByPracticeAppointmentId(practiceAppointmentId);
    }

    /**
     * 查询实践预约列表
     *
     * @param practiceAppointment 实践预约
     * @return 实践预约
     */
    @Override
    public List<PracticeAppointment> selectPracticeAppointmentList(PracticeAppointment practiceAppointment) {
        return practiceAppointmentMapper.selectPracticeAppointmentList(practiceAppointment);
    }

    /**
     * 新增实践预约
     *
     * @param practiceAppointment 实践预约
     * @return 结果
     */
    @Override
    public int insertPracticeAppointment(PracticeAppointment practiceAppointment) {
        practiceAppointment.setCreateTime(DateUtils.getNowDate());
        return practiceAppointmentMapper.insertPracticeAppointment(practiceAppointment);
    }

    /**
     * 新增实践预约并关联班级
     */
    @Transactional
    @Override
    public int insertPracticeAppointmentWithClass(PracticeAppointmentDto practiceAppointmentDto) {
        // 1. 生成实践预约ID
        practiceAppointmentDto.setPracticeAppointmentId(String.valueOf(snowflake.nextId()));

        // 2. 设置默认值 报名人数
        if (practiceAppointmentDto.getRegistrationNum() == null) {
            practiceAppointmentDto.setRegistrationNum(0);
        }
        // 初始状态：未实践、未报满
        if (practiceAppointmentDto.getPracticalType() == null) {
            practiceAppointmentDto.setPracticalType("0");
        }
        if (practiceAppointmentDto.getAppointmentType() == null) {
            practiceAppointmentDto.setAppointmentType("0");
        }
        //删除标志
        if (practiceAppointmentDto.getDelTag() == null) {
            practiceAppointmentDto.setDelTag("0"); // 0代表存在
        }
        //set创建者
        practiceAppointmentDto.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        //创建时间
        practiceAppointmentDto.setCreateTime(new Date());

        // 3. 保存实践预约主信息
        int result = practiceAppointmentMapper.insertPracticeAppointment(practiceAppointmentDto);

        // 4. 处理班级关联
        handleClassAssociation(practiceAppointmentDto);

        return result;
    }

    /**
     * 修改实践预约
     *
     * @param practiceAppointment 实践预约
     * @return 结果
     */
    @Override
    public int updatePracticeAppointment(PracticeAppointment practiceAppointment) {
        practiceAppointment.setUpdateTime(DateUtils.getNowDate());
        return practiceAppointmentMapper.updatePracticeAppointment(practiceAppointment);
    }

    /**
     * 批量删除实践预约
     *
     * @param practiceAppointmentIds 需要删除的实践预约主键
     * @return 结果
     */
    @Override
    public int deletePracticeAppointmentByPracticeAppointmentIds(String[] practiceAppointmentIds) {
        return practiceAppointmentMapper.deletePracticeAppointmentByPracticeAppointmentIds(practiceAppointmentIds);
    }

    /**
     * 删除实践预约信息
     *
     * @param practiceAppointmentId 实践预约主键
     * @return 结果
     */
    @Override
    public int deletePracticeAppointmentByPracticeAppointmentId(String practiceAppointmentId) {
        return practiceAppointmentMapper.deletePracticeAppointmentByPracticeAppointmentId(practiceAppointmentId);
    }


    /**
     * 条件查询实践预约列表
     * lqx
     */
    @Override
    public List<PracticeAppointmentVo> selectPracticeAppointmentListByQuery(PracticeAppointmentDto practiceAppointmentDto) {
        List<PracticeAppointmentVo> practiceAppointmentVos = new ArrayList<>();
        // 如果传入了项目名称，则先查询匹配的项目ID
        List<String> projectIds = null;
        if (StringUtils.isNotBlank(practiceAppointmentDto.getProjectName())) {
            // 构建项目查询条件（假设Projects类有projectName字段用于模糊查询）
            Projects projectQuery = new Projects();
            // 设置项目名称作为查询条件（通常配合Mapper层的like查询）
            projectQuery.setProjectName(practiceAppointmentDto.getProjectName());
            // 查询匹配的项目列表
            List<Projects> projectList = projectsService.selectProjectsList(projectQuery);
            // 如果没有匹配的项目，直接返回空列表
            if (CollectionUtils.isEmpty(projectList)) {
                return new ArrayList<PracticeAppointmentVo>();
            }
            // 提取项目ID列表（转换类型，解决类型不匹配问题）
            projectIds = projectList.stream()
                    .map(Projects::getProjectId)  // 假设Projects类有getProjectId()方法
                    .collect(Collectors.toList());
        }
        //获取符合条件的list
        List<PracticeAppointment> practiceAppointmentList = practiceAppointmentMapper.selectByCondition(practiceAppointmentDto, projectIds);
        for (PracticeAppointment practiceAppointment : practiceAppointmentList) {
            System.out.println("practiceAppointment = " + practiceAppointment);
            PracticeAppointmentVo practiceAppointmentVo = new PracticeAppointmentVo();
            //将practiceAppointment赋值给practiceAppointmentVo
            BeanUtils.copyProperties(practiceAppointment, practiceAppointmentVo);
            // TODO: 2025/10/15 教师资源库查询教师信息
            //查询教师信息
            String practicalTeacherId = practiceAppointmentVo.getPracticalTeacherId();
            practiceAppointmentVo.setPracticalTeacherName("张三");
            //查询项目名称
            Projects projects = projectsService.selectProjectsByProjectId(practiceAppointmentVo.getPracticalProjectId());
            practiceAppointmentVo.setPracticalProjectName(projects.getProjectName());
            //处理实践状态
            if (practiceAppointmentVo.getPracticalType() != null && !"".equals(practiceAppointmentVo.getPracticalType())) {
                if ("0".equals(practiceAppointmentVo.getPracticalType())) {
                    practiceAppointmentVo.setPracticalTypeName("未实践");
                }
                if ("1".equals(practiceAppointmentVo.getPracticalType())) {
                    practiceAppointmentVo.setPracticalTypeName("已实践");
                }
            }
            //处理预约情况
            if (practiceAppointmentVo.getAppointmentType() != null && !"".equals(practiceAppointmentVo.getAppointmentType())) {
                if ("0".equals(practiceAppointmentVo.getAppointmentType())) {
                    practiceAppointmentVo.setAppointmentTypeName("未报满");
                }
                if ("1".equals(practiceAppointmentVo.getAppointmentType())) {
                    practiceAppointmentVo.setAppointmentTypeName("已报满");
                }
            }
            //计算预约人数
            PracticeClassStudent practiceClassStudent = new PracticeClassStudent();
            practiceClassStudent.setPracticeAppointmentId(practiceAppointment.getPracticeAppointmentId());
            practiceClassStudent.setAppointmentStatus("0");
            List<PracticeClassStudent> practiceClassStudentList = practiceClassStudentMapper.selectPracticeClassStudentList(practiceClassStudent);
            practiceAppointmentVo.setRegistrationNum(practiceClassStudentList.size());
            System.out.println("RegistrationNum = " + practiceAppointmentVo.getRegistrationNum());
            //修改预约人数
            PracticeAppointment practiceAppointment1 = new PracticeAppointment();
            practiceAppointment1.setPracticeAppointmentId(practiceAppointment.getPracticeAppointmentId());
            practiceAppointment1.setRegistrationNum(practiceAppointmentVo.getRegistrationNum());
            practiceAppointmentMapper.updatePracticeAppointment(practiceAppointment1);
            //关联班级,通过实践id查询出实践班级表中的班级id并封装到数组中
            PracticeClass practiceClass = new PracticeClass();
            practiceClass.setPracticeAppointmentId(practiceAppointmentVo.getPracticeAppointmentId());
            List<PracticeClass> practiceClassList = practiceClassService.selectPracticeClassList(practiceClass);
            // 初始化List<TrainingClass>集合
            List<TrainingClass> trainingClassList = new ArrayList<>();
            // 遍历列表，提取班级id并查询班级详细信息
            for (PracticeClass aClass : practiceClassList) {
                // 获取班级id
                String trainingClassId = aClass.getTrainingClassId();
                // 查询班级信息
                TrainingClass trainingClass = trainingClassService.selectTrainingClassByTrainingClassId(trainingClassId);
                trainingClassList.add(trainingClass);
            }
            practiceAppointmentVo.setTrainingClassList(trainingClassList);

            //新增一条
            practiceAppointmentVos.add(practiceAppointmentVo);
        }
        return practiceAppointmentVos;
    }

    /**
     * 通过班级id查询实践预约列表
     * lqx
     */
    @Override
    public List<PracticeAppointmentVo> selectListByClassId(String classId) {
        //new一个List<PracticeAppointmentVo>返回
        List<PracticeAppointmentVo> practiceAppointmentVos = new ArrayList<>();
        //new一个实践预约班级的对象
        PracticeClass practiceClass = new PracticeClass();
        practiceClass.setTrainingClassId(classId);
        //通过班级id查询对应的实践预约id
        List<PracticeClass> practiceClassList = practiceClassService.selectPracticeClassList(practiceClass);
        if (practiceClassList != null && !practiceClassList.isEmpty()) {
            for (PracticeClass practiceClass1 : practiceClassList) {
                //new一个practiceAppointmentVo对象
                PracticeAppointmentVo practiceAppointmentVo = new PracticeAppointmentVo();
                //通过实践预约id去查询实践预约信息
                PracticeAppointment practiceAppointment = practiceAppointmentMapper.selectPracticeAppointmentByPracticeAppointmentId(practiceClass1.getPracticeAppointmentId());
                //将practiceAppointment的值复制给practiceAppointmentVo
                BeanUtils.copyProperties(practiceAppointment, practiceAppointmentVo);
                // TODO: 2025/10/15 教师资源库查询教师信息
                //查询教师信息
                String practicalTeacherId = practiceAppointmentVo.getPracticalTeacherId();
                practiceAppointmentVo.setPracticalTeacherName("张三");
                practiceAppointmentVos.add(practiceAppointmentVo);
            }
        }

        return practiceAppointmentVos;
    }

    @Override
    public int editPracticeAppointment(PracticeAppointmentDto practiceAppointmentDto) {
        //1.通过主键id修改基础信息
        //set修改者
        practiceAppointmentDto.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
//        practiceAppointmentDto.setUpdateBy("张三");
        //set修改时间
        practiceAppointmentDto.setUpdateTime(new Date());
        //调修改方法
        int result = practiceAppointmentMapper.updatePracticeAppointment(practiceAppointmentDto);

        //2.修改班级信息
        //先删除当前实践预约表id删除对应内容
        practiceClassService.deletePracticeClassByPracticeAppointmentId(practiceAppointmentDto.getPracticeAppointmentId());
        //处理班级关联
        handleClassAssociation(practiceAppointmentDto);
        return result;
    }

    /**
     * 删除实践预约(分配班级)
     * lqx
     */
    @Override
    public int removePracticeAppointmentByPracticeAppointmentIds(String[] practiceAppointmentIds) {
        //1.先将选中删除的数据在实践预约表中逻辑删除
        int result = practiceAppointmentMapper.removePracticeAppointmentByPracticeAppointmentIds(practiceAppointmentIds);
        //2.再通过实践预约id将实践预约表班级表中间表中对应的数据物理删除
        int i = practiceClassService.deletePracticeClassByPracticeAppointmentIds(practiceAppointmentIds);
        return result;
    }

    //处理班级关联
    public void handleClassAssociation(PracticeAppointmentDto practiceAppointmentDto){
        String[] trainingClassIds = practiceAppointmentDto.getTrainingClassIds();
        if (trainingClassIds != null && trainingClassIds.length > 0) {
            for (String trainingClassId : trainingClassIds) {
                PracticeClass practiceClass = new PracticeClass();
                practiceClass.setPracticeAppointmentId(practiceAppointmentDto.getPracticeAppointmentId());
                practiceClass.setTrainingClassId(trainingClassId);
                practiceClass.setRemarks(practiceAppointmentDto.getRemarks());
                practiceClass.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
//                practiceClass.setCreateBy("张三");
                // 保存关联信息
                practiceClassService.insertPracticeClass(practiceClass);
            }
        }
    }


}
